/*
 * Author: Alvin
 * Modified By: Alvin
 * Created Date: 2024-05-10 16:02:32
 * Last Modified: 2024-05-13 11:41:55
 * Description:
 */
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/select_phone_widget.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/low_code/enum/form_item_type.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/remark_widget.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';

///
/// @Description TODO
/// @Author liuer
/// @CreateTime 2023年12月12日 17:39
// ignore: must_be_immutable
class SingleformItemwidget extends StatefulWidget {
  SingleformItemwidget({
    Key? key,
    required this.title,
    this.hintTextString,
    required this.valueSetCallBack,
    required this.controller,
    required this.type,
    this.subTitle,
    this.keyboardType = TextInputType.number,
    this.selectList,
    this.maxValue = double.maxFinite,
    this.minValue = 0,
    this.value = '',
    this.rightSlot,
    this.leftSlot,
    this.isRequired = true,
    this.titleWidth = 150,
    this.isCanEdit = true,
    this.maxLines = 1,
    this.suffixIcon,
    this.maxLength = 100,
    this.maxPhotoCount = 3,
  }) : super(key: key);

  // 是否必填
  bool isRequired;
  // 标题
  final String title;
  // 副标题
  final String? subTitle;
  // 提示文字
  final String? hintTextString;
  // 输入框的回调
  final Function(dynamic value) valueSetCallBack;
  // 键盘类型
  final TextInputType keyboardType;
  // 输入框的controller
  final TextEditingController controller;
  // 输入框类型
  final int type;
  // 选择框的数据 /
  List? selectList;
  // 最大值
  final double? maxValue;
  // 最小值
  final double? minValue;
  // 输入框的值
  String value;
  // 右侧的widget
  final Widget? rightSlot;
  // 左侧的widget
  final Widget? leftSlot;
  final double? titleWidth;
  final bool isCanEdit; //是否可以响应输入
  final int maxLines; //最大行数
  final Widget? suffixIcon; // textfiled后缀图标
  final int maxLength; // 可输入的最大长度
  final int maxPhotoCount; // 可上传的最大图片数量
  @override
  State createState() => _SingleFormItemState();
}

class _SingleFormItemState extends State<SingleformItemwidget> {
  bool inputIsRight = true;
  bool keyboardIsShow = false;
  FormItemType get paramType => FormItemType.fromType(widget.type);
  bool get isOpen => widget.value == '0' ? false : true;
  @override
  void initState() {
    if (paramType == FormItemType.selectInput && widget.value.isNotEmpty) {
      for (var element in widget.selectList!) {
        if (element['value'] == int.parse(widget.value)) {
          widget.controller.text = element['name'];
        }
      }
    } else {
      widget.controller.text = widget.value;
    }

    // TODO: implement initState
    widget.controller.addListener(() {
      if (paramType == FormItemType.textInput && widget.controller.text.isNotEmpty) {
        inputIsRight = checkInputIsRight();
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void didUpdateWidget(covariant SingleformItemwidget oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if (oldWidget.value != widget.value) {
      if (paramType == FormItemType.selectInput) {
        for (var element in widget.selectList!) {
          if (element['value'] == int.parse(widget.value)) {
            widget.controller.text = element['name'];
          }
        }
      } else {
        widget.controller.text = widget.value;
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    widget.controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    switch (paramType) {
      case FormItemType.textInput:
        return _buildInputTextFormItem(context);
      case FormItemType.swich:
        return _buildSwichFormItem(context);
      case FormItemType.selectInput:
        return _buildInputTextFormItem(context);
      case FormItemType.time:
        return _buildInputTextFormItem(context);
      case FormItemType.date:
        return _buildInputTextFormItem(context);
      case FormItemType.dateTime:
        return _buildInputTextFormItem(context);
      case FormItemType.imageUpload:
        return _buildSelectPhotoFormItem(context);
      case FormItemType.textArea:
        return _buildTextAreaFormItem(context);
      case FormItemType.address:
        return _buildInputTextFormItem(context);
      default:
        return Container();
    }
  }

  Widget _buildInputTextFormItem(BuildContext context) {
    return Column(
      children: [
        SizedBox(
          height: 44,
          child: Row(
            children: [
              widget.isRequired
                  ? Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(
                        left: 6.w,
                        right: 2.w,
                      ),
                      child: Text(
                        '*',
                        style: ytTextStyle(
                          color: Colour.warningTextColor,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    )
                  : Gaps.hGap16,
              widget.leftSlot ?? Container(),
              SizedBox(
                // color: Colors.red,
                width: widget.titleWidth,
                child: Text(
                  widget.title,
                  maxLines: 2,
                  style: ytTextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.normal,
                    color: Colour.mainTextColor,
                  ),
                ),
              ),
              const Spacer(),
              SizedBox(
                width: widget.titleWidth,
                child: _buildTextField(context),
              ),
              SizedBox(width: widget.leftSlot == null ? 0 : 10),
              widget.rightSlot ?? Container(),
              const SizedBox(
                width: 15,
              )
            ],
          ),
        ),
        paramType == FormItemType.textInput
            ? Container(
                height: inputIsRight ? 1 : 15,
                margin: const EdgeInsets.only(right: 24, bottom: 2, top: 2),
                alignment: Alignment.centerRight,
                child: Visibility(
                  visible: !inputIsRight,
                  child: Text(
                    '${'Correct value range:'.tr}  ${widget.hintTextString}',
                    style: const TextStyle(color: Color(0xFFFA3F3F), fontSize: 10, height: 1.4),
                  ),
                ),
              )
            : Container(),
      ],
    );
  }

  Widget _buildSwichFormItem(BuildContext context) {
    return Row(
      children: [
        Container(
          margin: const EdgeInsets.only(left: 24),
          child: Text(
            widget.title,
            style: TextStyle(color: Colors.white, fontSize: 12.sp, fontWeight: FontWeight.bold),
          ),
        ),
        const Spacer(),
        Switch(
            value: isOpen,
            onChanged: (bool open) async {
              widget.value = open ? '1' : '0';
              setState(() {});
              widget.valueSetCallBack(open ? 1 : 0);
            },
            activeColor: Colour.primaryColor,
            inactiveThumbColor: Colour.gray74Color),
        const SizedBox(
          width: 8,
        ),
      ],
    );
  }

  // Widget _buildSelectFormItem(BuildContext context) {
  //   return Container();
  // }

  Widget _buildTextField(BuildContext context) {
    return TextField(
      textAlign: TextAlign.right,
      textAlignVertical: TextAlignVertical.center,
      maxLines: widget.maxLines,
      style: const TextStyle(fontSize: 12, color: Colour.otherTextColor, height: 1.2)
          .copyWith(textBaseline: TextBaseline.alphabetic),
      controller: widget.controller,
      keyboardType: widget.keyboardType,
      inputFormatters: [LengthLimitingTextInputFormatter(6)],
      decoration: InputDecoration(
        contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 0),
        border: InputBorder.none,
        hintText: widget.hintTextString,
        suffixIcon: widget.suffixIcon,
      ),
      onChanged: (String str) {
        widget.value = str;
        setState(() {});
      },
      onTap: () {
        switch (paramType) {
          case FormItemType.time:
            selectTime(widget.value, context, (String value) {
              widget.value = widget.controller.text = value;
              setState(() {});
            });
            break;
          case FormItemType.selectInput:
            List nameList = widget.selectList!
                .map(
                  (e) => e['name'].toString(),
                )
                .toList();
            showBottomPop(widget.title, 0, nameList, (index) {
              widget.value = widget.selectList![index]['value'].toString();
              widget.controller.text = widget.selectList![index]['name'];
              setState(() {});
            });
            break;
          case FormItemType.textInput:
            break;
          case FormItemType.address:
            gotoMap();
            break;
          default:
        }
      },
      onEditingComplete: () {
        inputIsRight = checkInputIsRight();
        setState(() {});
      },
    );
  }

  bool checkInputIsRight() {
    String value = widget.controller.text;
    if (widget.keyboardType == TextInputType.number &&
        (int.parse(value) > widget.maxValue! || int.parse(value) < widget.minValue!)) return false;

    return true;
  }

  ///选择时间
  void selectTime(initialTime, BuildContext context, Function(String) dateCallback) {
    FocusScope.of(context).requestFocus(FocusNode());
    if (initialTime == null) {
      initialTime = DateTime.now();
    } else {
      var hours = int.parse(initialTime.split(':')[0]);
      var minutes = int.parse(initialTime.split(':')[1]);
      var time = DateTime(2023, 5, 28, hours, minutes);
      initialTime = time;
    }

    BrnDatePicker.showDatePicker(
      context,
      themeData: BrnPickerConfig(
          confirmTextStyle: BrnTextStyle(color: const Color(0xFF666666)),
          itemTextStyle: BrnTextStyle(color: const Color(0xFF666666))),
      pickerMode: BrnDateTimePickerMode.time,
      rootNavigator: true,
      initialDateTime: initialTime,
      pickerTitleConfig: BrnPickerTitleConfig(
          cancel: Text(
            'Cancel'.tr,
            style: TextStyle(color: Colour.primaryLightColor, fontSize: 14.sp),
          ),
          confirm: Text(
            'OK'.tr,
            style: TextStyle(color: Colour.primaryLightColor, fontSize: 14.sp),
          ),
          titleContent: "Select Time".tr),
      dateFormat: "HH:mm",
      onConfirm: (DateTime dateTime, List<int> list) {
        if (list.length >= 2) {
          String hour = list.first.toString();
          if (list.first <= 9) {
            hour = '0$hour';
          }
          String minute = list[1].toString();
          if (list[1] <= 9) {
            minute = '0$minute';
          }
          dateCallback('$hour:$minute');
        }
      },
    );
  }

  ///弹出底部弹窗
  showBottomPop(String title, int selectedIndex, List list, Function(int index) callBack) {
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    BrnMultiDataPicker(
      context: Get.context!,
      title: title,
      confirmClick: (indexList) {
        callBack(indexList[0]);
      },
      themeData: BrnPickerConfig(
        itemTextStyle: BrnTextStyle(
          color: const Color(0xFF828222),
        ),
        cancelTextStyle: BrnTextStyle(
          color: const Color(0xFF828282),
        ),
      ),
      delegate: Brn1RowDelegate(list as List<String>, firstSelectedIndex: selectedIndex),
    ).show();
  }

  Widget _buildSelectPhotoFormItem(BuildContext context) {
    List<String> dataList = widget.selectList!.isEmpty ? [] : widget.selectList!.map((e) => e.toString()).toList();
    return SelectPhotoWidget(dataList, widget.isCanEdit, widget.maxPhotoCount,
        decString: widget.subTitle ?? '', titleString: widget.title, (List<String> list) {
      widget.selectList = list;
      setState(() {});
    });
  }

  Widget _buildTextAreaFormItem(BuildContext context) {
    return RemarkWidget(
      widget.controller,
      ((str) {
        widget.value = str;
        setState(() {});
      }),
      isCanEdit: widget.isCanEdit,
    );
  }

  ///跳转到地图页面
  void gotoMap() {
    Get.toNamed(RouterPath.amapPage, arguments: {})?.then((value) {
      if (value is AmapPoi) {
        widget.value = "${value.latitude},${value.longitude}";
        widget.controller.text = value.formattedAddress ?? '';
        setState(() {});
      }
    });
  }
}
